package com.youi.web;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.service.GroupleaderService;
import com.youi.service.LeaderfanService;
import com.youi.service.LeaderstoreService;
import com.youi.service.SmscodeService;
import com.youi.service.StoreService;
import com.youi.entity.Groupleader;
import com.youi.entity.Leaderfan;
import com.youi.entity.Leaderstore;
import com.youi.entity.Smscode;
import com.youi.entity.Store;
import com.youi.entity.User;
import com.youi.common.Common;
import com.youi.util.CommonInfoUtil;
import com.youi.util.DateUtil;
import com.youi.util.JedisUtils;
import com.youi.util.JsonUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.Page;
import com.youi.util.SmsUtil;

/**
* 团长信息控制层
* @author Administrator
*/
@Controller
public class GroupleaderController  extends HttpRequestManage{

		@Autowired
		private GroupleaderService groupleaderService;
		@Autowired
		private StoreService storeService;
		@Autowired
		private LeaderstoreService leaderstoreService;
		@Autowired
		private LeaderfanService leaderfanService;
		@Autowired
		private SmscodeService smscodeService;
		
		/**
		 *添加或编辑团长信息
		*/
		@ResponseBody
		@RequestMapping("addOrEditGroupleader")
		public String addOrEditGroupleader(ModelMap modelMap,HttpServletRequest request)throws BusinessException,ParseException{
			Long id=optLong("id",request);
			Groupleader groupleader=null;
			if (id!=null) {
				groupleader=groupleaderService.get(id);
			}else {
				groupleader=new Groupleader();
				groupleader.setDelStatus(DelStatus.NODEL);
				groupleader.setGmtCreated(new Date());
			}
			Long userId=optLong("userId",request);
			if (userId!=null){
				groupleader.setUserId(userId);
			}
			String name=optString("name",request);
			if (name!=null){
				groupleader.setName(name);
			}
			groupleader.setGmtModify(new Date());
			groupleaderService.saveOrUpdate(groupleader);
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
		}
		
					   
					
		
		/**
		 * M-19
		 * 门店认证
		 * @param modelMap
		 * @param request
		 * @return
		 * @throws BusinessException
		 * @throws ParseException
		 */
	    @ResponseBody
	    @RequestMapping("userGetInfo/checkStoreLeader")
	    public String checkStoreLeader(ModelMap modelMap,HttpServletRequest request) throws BusinessException{	
			String storeCode=getString("storeCode", request);
			String code=getString("code", request);
			String phone=getString("phone", request);
			User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);	
			if (user.getPhone()==null) {
				return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "请获取手机号后认证");
			}
			Map<String, Object> params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put(Common.USERID, user.getId());
			Map<String, Object> sortParams=new HashMap<String, Object>();
			sortParams.put(Common.ID, Common.ASC);
			Map<String, Object> startTime=new HashMap<String, Object>();
			startTime.put(Common.GMTCREATED,DateUtil.simpdfyMdHms.format(DateUtil.getCalendarByAdd(new Date(), Calendar.MINUTE, -1)));
			Smscode smscode=smscodeService.getByParamss(params, null, null, startTime, null);
			if (smscode==null) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "短信验证码已失效");
			}
			if (!smscode.getPhone().equals(phone)) {
				return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "验证手机号码不一致");
			}
			if (!smscode.getCode().equals(code)) {
				return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "验证码错误不一致");
			}
			smscode.setDelStatus(DelStatus.DEL);
			smscodeService.saveOrUpdate(smscode);
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put(Common.USERID, user.getId());
			Groupleader groupleader=groupleaderService.getByParam(params);
			if (groupleader==null) {
				groupleader=new Groupleader(user.getId(), user.getNickName(), user.getImg());
				groupleaderService.saveOrUpdate(groupleader);
			}
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put("code", storeCode);
			Store store=storeService.getByParam(params);
			if (store==null) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "门店不存在");
			}
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put("leaderId", groupleader.getId());
			params.put("storeId", store.getId());
			params.put("identity", 1);
			params.put("level", 1);
			Leaderstore topLeaderstore=leaderstoreService.getByParam(params);
			if (topLeaderstore!=null) {
				return JsonUtil.toJson(CommonInfoUtil.OBJECTEXIST, "门店已认证或已成为该店顶级团长");
			}
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put("leaderId", groupleader.getId());
			params.put("identity", 0);
			params.put("level", 2);
			Leaderstore leaderstore=leaderstoreService.getByParam(params);
			if (leaderstore!=null) {
				leaderstore.setDelStatus(DelStatus.DEL);
				leaderstoreService.saveOrUpdate(leaderstore);
			}
			leaderstore=new Leaderstore(groupleader.getId(), store.getId(), phone, store.getName(), store.getCode());
			leaderstore.setLevel(1);
			leaderstore.setIdentity(1);
			leaderstoreService.saveOrUpdate(leaderstore);
			user.setLeaderId(leaderstore.getLeaderId());
			if (leaderstore.getLevel()==1) {
				user.setLeaderLevel(1);						
			}else if (leaderstore.getLevel()==2) {
				user.setLeaderLevel(2);
			}
			HttpSessionManage.setAttribute(request, SessionKey.USER,user);
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");			
		}
		
		/**
		 * M-34
		 * 成为团长验证发送验证码
		 * @throws BusinessException 
		 */
		@ResponseBody
		@RequestMapping("userGetInfo/joinLeaderSendPhoneCode")
		public String registerSendPhoneCode(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
			if (user.getPhone()==null) {
				return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "请获取手机号后注册");
			}
			String phone=getString("phone", request);
			String authStoreCode=getString("storeCode", request);
			Map<String, Object> params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put("phone", phone);
			params.put("authStoreCode", authStoreCode);
			params.put("identity", 1);
			Leaderstore leaderstore=leaderstoreService.getByParam(params);
			if (leaderstore!=null) {
				return JsonUtil.toJson(CommonInfoUtil.OBJECTEXIST, "手机号已被认证");
			}
			params=new HashMap<String, Object>();
		    params.put(Common.DELSTATUS, DelStatus.NODEL);
		    params.put("mobile", phone);
		    params.put("code", authStoreCode);
		    Store store=storeService.getByParam(params);
		    if (store==null) {
		    	return JsonUtil.toJson(CommonInfoUtil.NOOPPMS, "不是店主手机号无法认证");
			}
			String code=SmsUtil.getRandom(6);
			String content="您认证的短信验证码是:"+code+"。为保障信息安全，请勿告诉他人。【美宜佳健康】";
			if (!SmsUtil.cloundSendMessage(content, phone)) {
				return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "短信发送失败");
			}
			smscodeService.saveOrUpdate(new Smscode(user.getId(),phone, code));
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
		}
		
		/**
		 * M-36
		 * 成为团长
		 * @throws BusinessException 
		 */
		@ResponseBody
		@RequestMapping("userGetInfo/becomeLeader")
		public String becomeLeader(ModelMap modelMap,HttpServletRequest request) throws BusinessException{			
			String storeCode=getString("storeCode", request);
			String storeName=getString("storeName", request);
			User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
			if (user.getPhone()==null&&user.getPhone().length()>0) {
				return JsonUtil.toJson(CommonInfoUtil.NULLSESSION, "用户手机号为空无法注册成为佳选官"); 
			}
			//1.验证门店是否存在
			Map<String, Object> params=new HashMap<String, Object>();
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put("code", storeCode);
			params.put("name", storeName);
			Store store=storeService.getByParam(params);
			if (store==null) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "门店不存在");
			}
			//2.验证团长信息是否有若没有则新增团长信息
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put(Common.USERID, user.getId());
			Groupleader groupleader=groupleaderService.getByParam(params);
			if (groupleader==null) {
				groupleader=new Groupleader(user.getId(), user.getNickName(), user.getImg());
				groupleaderService.saveOrUpdate(groupleader);
			}
			//验证团长是否成为顶级团长如果成为顶级团长则无法成为二级团长
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put("leaderId", groupleader.getId());
			params.put("level", 1);
			List<Leaderstore> leaderstoreList=leaderstoreService.getByParams(params);
			if (leaderstoreList!=null&&leaderstoreList.size()>0) {
				return JsonUtil.toJson(CommonInfoUtil.OBJECTEXIST, "已成为顶级团长无法成为普通团长");
			}
			//验证是否有重复注册
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put("leaderId", groupleader.getId());
			params.put("storeId", store.getId());
			List<Leaderstore> otherLeaderstoreList=leaderstoreService.getByParams(params);
			if (otherLeaderstoreList!=null&&otherLeaderstoreList.size()>0) {
				return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "请不要重复注册佳选官");
			}
			//4.绑定认证的门店
			Leaderstore leaderstore=new Leaderstore(groupleader.getId(), store.getId(), user.getPhone(), store.getName(), storeCode); 
			//5.判断用户手机号是否匹配门店手机号若匹配则成为顶级团长
			if (user.getPhone().equals(store.getMobile().trim())) {
				//判断该手机是否注册了该门店的顶级佳选官
				params=new HashMap<String, Object>();
				params.put(Common.DELSTATUS, DelStatus.NODEL);
				params.put("phone", user.getPhone());
				params.put("storeId", store.getId());
				params.put("level", 1);
				Leaderstore checkShopkeeper=leaderstoreService.getByParam(params);
				if (checkShopkeeper!=null) {
					groupleaderService.delete(groupleader);
					return JsonUtil.toJson(CommonInfoUtil.OBJECTEXIST, "该手机号已被使用，如你是该店店主，请联系指导员，如不是请填写新号码，继续成为佳选官"); 
				}
				leaderstore.setLevel(1);
				leaderstore.setIdentity(1);
			}else {
				//若不匹配则查找本店顶级团长
				params=new HashMap<String, Object>();
				params.put(Common.DELSTATUS, DelStatus.NODEL);
				params.put("storeId", store.getId());
				params.put("level", 1);
				Leaderstore topleader=leaderstoreService.getByParam(params);
				if (topleader==null) {
					//若顶级团长不存在则无法成为二级团长并删除团长信息中断操作
					groupleaderService.delete(groupleader);
					return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "该店尚未开通佳选官服务,如您是店主,请使用店主手机认证开通。"); 
				}
				//若存在顶级团长则成为本店二级团长
				leaderstore.setLevel(2);
				leaderstore.setIdentity(0);
			}
			leaderstoreService.saveOrUpdate(leaderstore);
			user.setLeaderId(leaderstore.getLeaderId());
			if (leaderstore.getLevel()==1) {
				user.setLeaderLevel(1);						
			}else if (leaderstore.getLevel()==2) {
				user.setLeaderLevel(2);
			}
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);			
			params.put("unionid", user.getUnionId());
			Leaderfan leaderfan=leaderfanService.getByParam(params);
			if (leaderfan!=null) {
				leaderfan.setDelStatus(DelStatus.DEL);
				leaderfanService.saveOrUpdate(leaderfan);
			}
			HttpSessionManage.setAttribute(request, SessionKey.USER,user);
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
		}
		
		/**
		 *批量删除团长信息
		*/
		@ResponseBody
		@RequestMapping("delGroupleaderByIds")
		public String delGroupleaderByIds(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			String ids=getString("ids",request);
			List<Long> idsList=ObjectUtil.getIdListByIds(ids);
			if (idsList==null||idsList.size()==0) {
				return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
			}
			Map<String, Object> params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put(Common.ID, idsList);
			List<Groupleader> groupleaderList= groupleaderService.getByParams(params);
			if (groupleaderList==null||groupleaderList.size()==0) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			for (Groupleader groupleader : groupleaderList) {
				groupleader.setDelStatus(DelStatus.DEL);
			}
			groupleaderService.saveOrUpdateAll(groupleaderList);
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
		}

		/**
		 * 分页查询团长信息
		*/
		@ResponseBody
		@RequestMapping("getGroupleader")
		public String getGroupleader(ModelMap modelMap,HttpServletRequest request) throws BusinessException,ParseException{
			Integer pageIndex=optInteger("pageIndex",request,1);
			Integer pageNum=optInteger("pageNum",request,10);
			String des=optString("des",request,Common.DESC);
			String pms=optString("pms",request);
			Date start=optDate("start",request,"yyyy-MM-dd HH:mm:ss");
			Date end=optDate("end",request,"yyyy-MM-dd HH:mm:ss");
			Map<String, Object> prams=new HashMap<String, Object>();
			prams.put(Common.DELSTATUS, DelStatus.NODEL);
			Map<String, Object> sortPram=new HashMap<String, Object>();
			sortPram.put(Common.ID,des);
			Map<String, Object> searchPram=null;
			if (pms!=null) {
				searchPram=new HashMap<String, Object>();
			}
			Map<String, Object> startTime=null;
			if(start!=null){
				startTime=new HashMap<String, Object>();
				startTime.put(Common.GMTCREATED,start);
			}
			Map<String, Object> endTime=null;
			if(end!=null){
				endTime=new HashMap<String, Object>();
				endTime.put(Common.GMTCREATED,end);
			}
			List<Groupleader> groupleaderList=groupleaderService.getByParamsList(prams, searchPram,sortPram,  (pageIndex-1)*pageNum, pageNum, startTime, endTime);
			if (groupleaderList==null||groupleaderList.size()==0) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			Integer pageCount=groupleaderService.getCountByParamss(prams, searchPram, startTime, endTime);
			modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数
			modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);			//pageIndex     查询页数
			modelMap.put(CommonInfoUtil.ALLCOUINT,pageCount);
			modelMap.put(CommonInfoUtil.DATA, groupleaderList);		//jsonObjectList json对象集合
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",modelMap);
		}

		/**
		 *根据id查询团长信息
		*/
		@ResponseBody
		@RequestMapping("getGroupleaderById")
		public String getGroupleaderById(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			Long id=getLong("id",request);
			Groupleader groupleader=groupleaderService.get(id);
			if (groupleader==null) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",groupleader);//jsonObject	json对象
		}

}
